package com.cu.employmentmanagementsystem.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.cu.employmentmanagementsystem.common.result.R;
import com.cu.employmentmanagementsystem.common.exception.CommonException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * @author 25853
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler
{
    private static final Logger LOGGER = Logger.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception exception)
    {
        String userId;
        try
        {
            userId = StpUtil.getLoginIdAsString();
        }
        catch (Exception e)
        {
            userId = "未知";
        }

        if (exception instanceof MethodArgumentNotValidException)
        {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) exception;
            BindingResult exceptions = ex.getBindingResult();
            // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
            if (exceptions.hasErrors())
            {
                List<ObjectError> errors = exceptions.getAllErrors();
                if (!errors.isEmpty())
                {
                    // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                    FieldError fieldError = (FieldError) errors.get(0);
                    LOGGER.error("用户" + userId + "参数校验异常：" + fieldError.getDefaultMessage());
                    return R.error(fieldError.getDefaultMessage());
                }
            }

        }
        if (exception instanceof CommonException)
        {
            LOGGER.error("用户" + userId + "操作异常：" + exception.getMessage());
            return R.error(exception.getMessage());
        }
        if (exception instanceof NotLoginException)
        {
            LOGGER.error("用户未登录：" + exception.getMessage());
            return R.notLogin("登录信息已过期，请重新登录！");
        }
        LOGGER.error("用户" + userId + "操作导致服务器运行时异常：" + exception.getMessage());
        exception.printStackTrace();
        return R.error("服务器异常，请向开发者反馈或请稍后再试~");
    }
}
